import logging
from fastapi import Request, HTTPException
from fastapi.responses import JSONResponse
from sqlalchemy.exc import IntegrityError, OperationalError
from jose import JWTError

logger = logging.getLogger(__name__)

async def database_exception_handler(request: Request, exc: OperationalError):
    """
    数据库连接异常处理
    """
    logger.error(f"Database connection error: {exc}")
    return JSONResponse(
        status_code=503,
        content={
            "detail": "Database connection error. Please try again later.",
            "error_type": "database_error"
        }
    )

async def integrity_exception_handler(request: Request, exc: IntegrityError):
    """
    数据库完整性约束异常处理
    """
    logger.error(f"Database integrity error: {exc}")
    return JSONResponse(
        status_code=400,
        content={
            "detail": "Data integrity error. The operation conflicts with existing data.",
            "error_type": "integrity_error"
        }
    )

async def jwt_exception_handler(request: Request, exc: JWTError):
    """
    JWT认证异常处理
    """
    logger.warning(f"JWT error: {exc}")
    return JSONResponse(
        status_code=401,
        content={
            "detail": "Invalid authentication credentials",
            "error_type": "authentication_error"
        }
    )

async def http_exception_handler(request: Request, exc: HTTPException):
    """
    HTTP异常处理
    """
    return JSONResponse(
        status_code=exc.status_code,
        content={
            "detail": exc.detail,
            "error_type": "http_error"
        }
    )

async def general_exception_handler(request: Request, exc: Exception):
    """
    通用异常处理
    """
    logger.error(f"Unexpected error: {exc}", exc_info=True)
    return JSONResponse(
        status_code=500,
        content={
            "detail": "Internal server error",
            "error_type": "internal_error"
        }
    )